package com.gt.web.srv.config;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import cn.binarywang.wx.miniapp.config.impl.WxMaRedisBetterConfigImpl;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.redis.RedisTemplateWxRedisOps;
import me.chanjar.weixin.common.redis.WxRedisOps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;

@Slf4j
@Configuration
@EnableConfigurationProperties(WxMaProperties.class)
public class WxMaConfiguration {

    private final WxMaProperties properties;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    public WxMaConfiguration(WxMaProperties properties) {
        this.properties = properties;
    }

    @Bean
    public WxRedisOps getWxRedisOps() {
        return new RedisTemplateWxRedisOps(stringRedisTemplate);
    }

    @Bean
    public WxMaService wxMaService() {
        WxMaService maService = new WxMaServiceImpl();
        if (properties != null) {
            WxMaDefaultConfigImpl config = new WxMaRedisBetterConfigImpl(getWxRedisOps(), "wx:token");
            // 使用上面的配置时，需要同时引入jedis-lock的依赖，否则会报类无法找到的异常
            config.setAppid(properties.getAppid());
            config.setSecret(properties.getSecret());
            config.setToken(properties.getToken());
            config.setAesKey(properties.getAesKey());
            config.setMsgDataFormat(properties.getMsgDataFormat());
            maService.setWxMaConfig(config);
        }
        return maService;
    }

}
